package admin.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.StaffModel;
import models.StoreModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.googlecode.objectify.annotation.Cached;

@Cached
public class StoreData {

	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "Store_";

	public StoreData() {
		try {
			ObjectifyService.register(StoreModel.class);
		} catch (Exception e) {
			// TODO: handle exception
		}

		try {
			cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e) {
			// e.printStackTrace();
		}

		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public List<StoreModel> getListStore()
	{
		List<StoreModel> list = new ArrayList<StoreModel>();
		Query<StoreModel> query = ofy.query(StoreModel.class);
		for (StoreModel store: query) {
			list.add(store);
		}
		return list;
	}
	
	public StoreModel getStore(String name) {
		StoreModel store = new StoreModel();
		if(cache.containsKey(prefix+name))
		{
			store = (StoreModel) cache.get(prefix+name);
		}
		else
		{
			try {
				store = ofy.get(new Key<StoreModel>(StoreModel.class, name));
				cache.put(prefix+name, store);
			} catch (Exception e) {
				store = null;
			}
		}
		return store;
	}
	
	public void insertStore(StoreModel store) {
		ofy.put(store);
	} 
}
